package com.jic.order.impl;

import com.jic.common.base.vo.RestResult;
import com.jic.order.base.BaseService;
import com.jic.order.enums.OrderEnum;
import com.jic.order.exception.OrderException;
import com.jic.order.response.EnumInfo;
import com.jic.order.service.EnumService;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class EnumServiceImpl extends BaseService implements EnumService {

	@Override
	public RestResult<List<EnumInfo>> getInfos(String enumName) {
		return executeQuery(new Query() {
			@Override
			public Object query() {
				try {
					// 根据枚举名找到枚举
					Class clazz = Class.forName(enumName);
					//获取values方法
					Method method = clazz.getMethod("values");
					//调用values方法得到所有枚举对象
					Object[] objs = (Object[]) method.invoke(null);
					List<EnumInfo> enumInfos = new ArrayList<>();
					for (Object obj : objs) {
						//反射获取getCode、getMessage方法
						Object code = obj.getClass().getMethod("getCode").invoke(obj);
						String message = (String) obj.getClass().getMethod("getMessage").invoke(obj);
						EnumInfo enumInfo = new EnumInfo();
						enumInfo.setCode(code);
						enumInfo.setMessage(message);
						enumInfos.add(enumInfo);
					}
					return enumInfos;
				} catch (Exception e) {
					throw new OrderException(OrderEnum.ENUM_EXECEPTION, "转化枚举失败" + enumName);
				}
			}
		});
	}

}

